package com.dux.commons.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * Object<==>Byte[]互转工具类
 * @author 杜祥
 *
 */
public class ByteObjectUtil {
	
	/**
	 * 序列化内容转换成java对象
	 * @param data			数据
	 * @return				返回对应的java对象
	 */
	@SuppressWarnings("unchecked")
	public static <T>T getObj(byte[] data){
		if (data == null || data.length == 0){
	      return null;
	    }
		T obj=null;
	    ByteArrayInputStream bis = new ByteArrayInputStream(data);
	    ObjectInputStream ois;
		try{
			ois = new ObjectInputStream(bis);
			obj =(T) ois.readObject();
			bis.close();
			ois.close();
		}catch(IOException e){
			e.printStackTrace();
		}catch(ClassNotFoundException e){
			e.printStackTrace();
		}
	    return obj;
	}
	
	/**
	 * 对象转换成Byte[]
	 * @param obj			对象
	 * @return				返回Byte
	 */
	public static <T extends Object>byte[] getBytes(T obj){
		byte[] bytes=null;
		ByteArrayOutputStream bos=new ByteArrayOutputStream();
		ObjectOutputStream oos;
		try {
			oos=new ObjectOutputStream(bos);
			oos.writeObject(obj);
			bytes=bos.toByteArray();
			bos.close();
			oos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bytes;
	}
}
